﻿using Note.Model;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace Note.View
{
    /// <summary>
    /// Interaction logic for MainContent.xaml
    /// </summary>
    public partial class MainContent : UserControl
    {
        public event EventHandler SelectChange;
        public MainContent()
        {
            InitializeComponent();
        }

        public void UpdateList(string type = "note", int position = 0)
        {
            this.DataList.Items.Clear();
            var datas = NoteModel.GetNodeDetailList(type)?.Notes;
            if (datas != null && datas.Count != 0)
            {
                foreach (var data in datas)
                {
                    this.DataList.Items.Add(data);
                }
                this.DataList.SelectedIndex = position;
                this.Content.Text = (this.DataList.SelectedItem as NoteDetailModel)?.Content;
            }
        }

        private void Select_Change(object sender, SelectionChangedEventArgs e)
        {
            var selectItem = (sender as ListBox)?.SelectedItem;
            Content.Text = (selectItem as NoteDetailModel)?.Content;
            SelectChange?.Invoke(selectItem, new EventArgs());
        }

        private void Control_Loaded(object sender, RoutedEventArgs e)
        {
            UpdateList();
        }

        private void Menu_Edit(object sender, RoutedEventArgs e)
        {
            var position = (int)((sender as MenuItem).CommandParameter);
            var model = this.DataList.Items[position] as NoteDetailModel;
            var type = model.Type;
            var dialog = new EditNoteDialog()
            {
                Value = false,
                Model = model
            };
            var result = dialog.ShowDialog();
            if (result == true)
            {
                UpdateList(type, position);
            }
        }

        private void Menu_Remove(object sender, RoutedEventArgs e)
        {
            var position = (int)((sender as MenuItem).CommandParameter);
            var model = this.DataList.Items[position] as NoteDetailModel;
            NoteModel.RemoveNoteDetailToList(model);
            this.DeleteFile(model.Path);
            UpdateList(model.Type, position == 0 ? 0: position - 1);
        }
    }
}
